﻿/*-----------------------------------------------------------------------
 * <copyright file="UserLog_Win.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Zhang jun</author>
 * <summary>
 *             登录窗体
 *     引用服务：WCFServers.WCFAccountsRef
 *     服务功能：数据查询
 *     
 *     引用服务：WCFLog4Ref.WCFLog4Client
 *     服务功能：记录日志
 * 
 *          作成日：05/21/2010
 *          新改版作成日：05/23/2011 v2.14
 *          
 *                  07/05/2010 增加 登录提示图标
 *                  07/08/2010 增加 读COOKIE功能 （现场）
 *                  07/20/2010 删除 读/写COOKIE功能 （ISO20007）
 *                  08/03/2010 增加 获取客户端IP地址
 *                  09/27/2010 增加 获取树形结构服务（从MainPage.xaml移植）
 *                  11/12/2010 增加 对各别用户添加各别权限
 *                 
 * </summary>
 *----------------------------------------------------------------------- 
 */


namespace Orid.Management.Statistics.OperatorUnitMangement.MainPageControl
{
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.FunctionList;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFServers.WCFAccountsRef;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;
    using Wcf = Orid.Management.Statistics.OperatorUnitMangement.Common.Service;


    /// <summary>
    /// 登录窗体
    /// UserLogWin
    /// </summary>
    public partial class UserLog_Win : UserControl
    {
        /// <summary>
        /// 当前页面的名字（日志用）
        /// </summary>
        private const string pageName = " 登录窗体 UserLogWin ";

        /// <summary>
        /// 消息子窗口
        /// MessageBox
        /// </summary>
        private childWindow.MessageBox messbox = new childWindow.MessageBox();

        /// <summary>
        /// 设置代理
        /// 数据查询的代理
        /// </summary>
        private WCFServers.WCFAccountsRef.WCFAccountsClient client;

        /// <summary>
        /// 日志代理
        /// WCFLog4Client
        /// </summary>
        private WCFLog4Ref.WCFLog4Client wcfLogClient;

        /// <summary>
        /// 记录用户是否登录成功
        /// 防止多次重复记录日志
        /// </summary>
        private bool isLogon;

        /// <summary>
        /// IP地址
        /// </summary>
        string IPAddress = null;

        /// <summary>
        /// 获取树形结构服务
        /// WCFAccountsClient
        /// </summary>
        /// <value>09/27/2010 Add </value>
        private WCFAccountsClient clientTreeView = null;

        /// <summary>
        /// 登录窗体
        /// UserLogWin
        /// </summary>
        public UserLog_Win()
        {
            InitializeComponent();

            this.client = Wcf.Service.Accounts;

            this.wcfLogClient = Wcf.Service.Log4;

            this.clientTreeView = new WCFAccountsClient();

            this.Loaded += new RoutedEventHandler(this.UserLogWin_Loaded);

            // 引用主题
            //((App)Application.Current).SetTheme((StackPanel)spButton);

            this.client.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(this.Client_GetLoginCompleted);

            // 键盘按下事件
            this.KeyDown -= new KeyEventHandler(this.UserLogWin_KeyDown);
            this.KeyDown += new KeyEventHandler(this.UserLogWin_KeyDown);

            this.messbox.Closed -= new EventHandler(this.MyMessBox_Closed);
            this.messbox.Closed += new EventHandler(this.MyMessBox_Closed);

            isLogon = true;

            //取得当前版本号  07/19/2010 -- ADD
            this.TitleVer.Text = FunctionClass.GetFormatedVersion(false);

            //08/03/2010 增加 获取客户端IP地址
            WCFServers.WCFAccountsRef.WCFAccountsClient wcfAccountClient = new Orid.Management.Statistics.OperatorUnitMangement.WCFServers.WCFAccountsRef.WCFAccountsClient();
            wcfAccountClient.IPAddressCompleted += new EventHandler<Orid.Management.Statistics.OperatorUnitMangement.WCFServers.WCFAccountsRef.IPAddressCompletedEventArgs>(wcfAccountClient_IPAddressCompleted);
            wcfAccountClient.IPAddressAsync();

            //09/27/2010 ADD
            // 树形结构 的服务委托
            this.clientTreeView.TreeViewListCompleted += new EventHandler<TreeViewListCompletedEventArgs>(this.ClientTreeView_TreeViewListCompleted);
            
        }


        #region 页面加载
        /// <summary>
        /// 页面加载
        /// UserLogWin_Loaded
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void UserLogWin_Loaded(object sender, RoutedEventArgs e)
        {
            // 验证控制数据源绑定
            this.UserValidation.DataContext = new UserLogValidation();

            //确定按钮有效
            this.OKButton.IsEnabled = true;

            #region 读取 本地 COOKIE 07/20/2010 删除 读COOKIE功能 （ISO20007）
#if DEBUG
            {
                int i = CookieHelper.GetCookies().Count;
                this.UserName.Text = CookieHelper.GetCookies()[i - 2];
                this.PassWord.Password = CookieHelper.GetCookies()[i - 1];
            }
#endif
            #endregion 读取 本地 COOKIE
        }
        #endregion 页面加载

        #region 确定按钮
        /// <summary>
        /// 确定按钮 
        /// OKButton_Click
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                BindingExpression expression = this.UserName.GetBindingExpression(TextBox.TextProperty);
                expression.UpdateSource();

                BindingExpression expression1 = this.PassWord.GetBindingExpression(PasswordBox.PasswordProperty);
                expression1.UpdateSource();

                if (this.vsValidationSummary.HasErrors)
                {
                    // 发现错误 停止执行 
                    if (this.UserName.Text.Length <= 0 || this.PassWord.Password.Length <= 0)
                    {
                        this.wcfLogClient.InfoAsync(IPAddress + ((App)Application.Current).LogStr + "用户登录失败！");
                        this.OKButton.IsEnabled = true;
                        isLogon = false;
                        return;
                    }
                }
                else
                {

                    #region  把用户信息写入COOKIES 07/20/2010 删除 读/写COOKIE功能 （ISO20007）
#if DEBUG
                    CookieHelper.SetCookie(this.UserName.Text, this.PassWord.Password);
#endif
                    #endregion   把用户信息写入COOKIES


                    // 继续执行
                    this.OKButton.IsEnabled = false;
                    this.UserName.IsEnabled = false;
                    this.PassWord.IsEnabled = false;

                    // 确定按钮无效
                    this.OKButton.IsEnabled = false;
                    // 调用登录
                    this.client.LoginAsync(this.UserName.Text.Trim().ToString(), this.PassWord.Password.ToString());
                    isLogon = true;
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(IPAddress + ((App)Application.Current).LogStr + pageName + "OKButton_Click（）方法" + ex.Message.ToString());
                this.OKButton.IsEnabled = true;
                this.UserName.IsEnabled = true;
                this.PassWord.IsEnabled = true;
                return;
            }
        }
        #endregion 确定按钮

        #region 取消按钮
        /// <summary>
        /// 取消按钮
        /// CancelButton_Click
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            
            this.wcfLogClient.InfoAsync(IPAddress + ((App)Application.Current).LogStr + "用户取消登录！");

            this.OKButton.IsEnabled = true;

            this.UserName.IsEnabled = true;
            this.PassWord.IsEnabled = true;

            isLogon = false;
            
        }
        #endregion 取消按钮

        #region WCFDecomposition.AccountsRef服务的相关方法
        /// <summary>
        /// 登录方法（事件）
        /// Client_GetLoginCompleted
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of LoginCompletedEventArgs</param>
        private void Client_GetLoginCompleted(object sender, LoginCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    if (!String.IsNullOrEmpty(e.Result.AccountID))
                    {
                        if (!String.IsNullOrEmpty(e.Result.OpName))
                        {
                            //this.ShowMessageBox("当前登录用户：" + e.Result.OpName.Trim(), 0);
                            if (isLogon == true)
                            {
                                this.wcfLogClient.InfoAsync(IPAddress + ((App)Application.Current).LogStr + "用户 " + e.Result.OpName.Trim() + "成功登录！");
                            }
                        }
                        else
                        {
                            //this.ShowMessageBox("当前登录用户：" + e.Result.AccountID.Trim(), 0);
                            if (isLogon == true)
                            {
                                this.wcfLogClient.InfoAsync(IPAddress + ((App)Application.Current).LogStr + "用户 " + e.Result.AccountID.Trim() + "成功登录！");
                            }
                        }

                        //日志记录完毕
                        isLogon = false;

                        //写入 已登入用户信息
                        ClientUserInfor.UserName = e.Result.AccountID.ToString().Trim();
                        ClientUserInfor.RoleName = FunctionClass.MyIsNullOrEmpty(e.Result.RoleName.Trim(), null);
                        ClientUserInfor.Condition = e.Result.Condition.ToString().Trim();
                        ClientUserInfor.UserRealName = FunctionClass.MyIsNullOrEmpty(e.Result.OpName.Trim(), null);
                        ClientUserInfor.DataBaseName = FunctionClass.MyIsNullOrEmpty(e.Result.DataBaseName.Trim(), null);

                        // 可以登录，但没有权限的用户，初始值为“0”
                        if (String.IsNullOrEmpty(e.Result.RoleID))
                        {
                            ClientUserInfor.RoleID = "0";
                        }
                        else
                        {
                            ClientUserInfor.RoleID = e.Result.RoleID.ToString().Trim();
                        }

                        #region 对各别用户添加各别权限
                        //11/12/2010 Add  ↓

                        // 孙雷普 sunleipu 增加 数据抽取（基礎データ，オーダ情報）27，28
                        FunctionClass.AddOrSubRoles("sunleipu", true, "2", "27", "28");

                        //孙丹 sundan 增加 数据抽取（基礎データ，オーダ情報）27，28
                        FunctionClass.AddOrSubRoles("sundan", true, "2", "27", "28");

                        //钱明霞 SYDY_qm  增加 数据抽取（基礎データ，オーダ情報）27，28
                        FunctionClass.AddOrSubRoles("SYDY_qm", true, "2", "27", "28");

                        //杨甫哲 sydy_yfzh 增加 数据抽取（基礎データ，オーダ情報）27，28
                        FunctionClass.AddOrSubRoles("sydy_yfzh", true, "2", "27", "28");
                        
                        // 11/12/2010 end ↑
                        #endregion 对各别用户添加各别权限

                        // 调用 形成树结构
                        this.clientTreeView.TreeViewListAsync(ClientUserInfor.Condition.ToString().Trim(), true);

                    }
                    else
                    {
                        this.ShowMessageBox("用户名或密码错误！", 1);
                        this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr + "用户登录失败！");

                        isLogon = false;

                        this.OKButton.IsEnabled = true;
                        this.UserName.IsEnabled = true;
                        this.PassWord.IsEnabled = true;
                    }
                }
                else
                {
                    this.ShowMessageBox(e.Error.Message, 1);
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(IPAddress + ((App)Application.Current).LogStr + pageName + ex.Message.ToString());
                isLogon = false;
                this.OKButton.IsEnabled = true;
                this.UserName.IsEnabled = true;
                this.PassWord.IsEnabled = true;
                return;
            }
        }
        #endregion

        #region 消息窗体相关方法

        /// <summary>
        /// 消息窗体关闭事件代码
        /// MyMessBox_Closed
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        private void MyMessBox_Closed(object sender, EventArgs e)
        {
            if (this.messbox.DialogResult == false)
            {
                this.PassWord.Password = string.Empty;
                this.UserName.Text = string.Empty;
            }
        }

        /// <summary>
        /// 弹出消息窗体
        /// 有自定义关闭事件，没有调用公用方法
        /// </summary>
        /// <param name="str">显示消息字符串</param>
        /// <param name="number">显示级别选择：【0】提示级 【1】错误级</param>
        private void ShowMessageBox(string str, int number)
        {
            // 消息子窗口
            this.messbox.Title = "登录信息";
            this.messbox.OverlayBrush = new SolidColorBrush(Colors.Gray);
            this.messbox.Opacity = 0.9;
            this.messbox.HasCloseButton = true;
            this.messbox.messboxText.TextWrapping = System.Windows.TextWrapping.Wrap;
            this.messbox.OverlayOpacity = 0.9;
            this.messbox.OKButton.Visibility = Visibility.Visible;
            BitmapImage bi = null;
            switch (number)
            {
                //提示级
                case 0:
                    this.messbox.Foreground = new SolidColorBrush(Colors.Blue);
                    this.messbox.messboxText.Text = str;
                    //-- 07/05/2010 -- ADD
                    bi = new BitmapImage(new Uri(((App)Application.Current).imageUriList[0].ToString(), UriKind.RelativeOrAbsolute));
                    messbox.ImageSource.Source = bi;
                    break;
                //错误级
                case 1:
                    this.messbox.Foreground = new SolidColorBrush(Colors.Red);
                    this.messbox.messboxText.Text = str;
                    //-- 07/05/2010 -- ADD
                    bi = new BitmapImage(new Uri(((App)Application.Current).imageUriList[1].ToString(), UriKind.RelativeOrAbsolute));
                    messbox.ImageSource.Source = bi;
                    break;
            }

            this.messbox.Show();
        }
        #endregion 消息窗体相关方法

        #region 键盘按下事件
        /// <summary>
        /// 键盘按下事件
        /// UserLogWin_KeyDown
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of KeyEventArgs</param>
        private void UserLogWin_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                return;
            }
            else
            {
                if (this.OKButton.IsEnabled == true)
                {
                    this.OKButton_Click(sender, e);
                }
            }
        }
        #endregion 键盘按下事件

        #region 获取客户端IP地址
        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        /// <value></value>
        void wcfAccountClient_IPAddressCompleted(object sender, Orid.Management.Statistics.OperatorUnitMangement.WCFServers.WCFAccountsRef.IPAddressCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    if (e.Result != null)
                    {
                        IPAddress = e.Result;
                    }
                }
            }
            catch
            {
                IPAddress = string.Empty;
            }
        }

        #endregion 获取客户端IP地址

        #region 树形结构 的服务现实
        /// <summary>
        /// 树形结构 的服务现实
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of  TreeViewListCompletedEventArgs</param>
        /// <value>09/27/2010 Add</value>
        private void ClientTreeView_TreeViewListCompleted(object sender, TreeViewListCompletedEventArgs e)
        {
            try
            {
                ClientDataList.IsURIAddress.Clear();
                ClientDataList.ClientTreeInforList.Clear();

                if (e.Error == null & e.Result.Count > 0)
                {
                    // 将服务端树形结构存储在客户端
                    foreach (WCFServers.WCFAccountsRef.TreeViewDataList tvdl in e.Result)
                    {
                        ClientDataList.ClientTreeInforList.Add(new ClientTreeInfor()
                        {
                            NodeID = tvdl.NodeID.ToString().Trim(),
                            NodeName = tvdl.NodeName.ToString().Trim(),
                            NodeParendID = tvdl.NodeParendID.ToString().Trim(),
                            TagUri = tvdl.TagUri.ToString().Trim(),
                            System = tvdl.System.ToString().Trim()
                        });
                        ClientDataList.IsURIAddress.Add(tvdl.TagUri.ToString().Trim());
                    }
                }
                // 进入MAIN 页面
                ((App)Application.Current).RedirectTo(new MainPage());
            }
            catch (Exception ex)
            {
                //确定按钮有效
                this.OKButton.IsEnabled = true;
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + " ClientTreeView_TreeViewListCompleted " + ex.Message.ToString());
                FunctionClass.ShowMessageBox(
                   this.messbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }

        }
        #endregion 树形结构 的服务现实


    }
}
